﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Enyim.Caching;
using Infrastructure;
using Infrastructure.Cache;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OpenAuth.App;
using OpenAuth.App.Request;
using OpenAuth.Hospital;
using OpenAuth.Hospital.Model;
using OpenAuth.Repository.Domain;

namespace OpenAuth.WebApi.Areas.HisApi.Controllers
{
    [Route("HisApi/[controller]/[action]")]
    [ApiController]
    public class PayBankZYController : ControllerBase
    {
        private ILog log = LogManager.GetLogger(typeof(PayBankController));
        //缓存
        private ICacheContext cache;
        private readonly QRPayApp qrApp;
        //门诊预交金预充值
        private readonly BMZXX006App bmzxx006App;
        private readonly BMZXX003App bmzxx003App;
        private readonly CGGYW007App cggyw007App;
        private readonly BMZXX009App bmzxx009App;
        //向本地表写入充值记录

        private readonly PayOrderZYApp payorderZYApp;
        //本地表退款记录
        private readonly RefundOrderApp refundOrderApp;
        private readonly PayToolsApp payToolsApp;
        //患者基本信息
        private readonly CMZXX001App cmzxx001App;
        private readonly CMZXX002App cMZXX002App;
        //private HospitalApi hospitalApi;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_qrApp"></param>

        /// <param name="_refundOrderApp"></param>
        /// <param name="_payToolsApp"></param>
        /// <param name="_bmzxx006App"></param>
        /// <param name="_bmzxx003App"></param>

        public PayBankZYController(QRPayApp _qrApp, PayOrderZYApp _payorderZYApp,/* HospitalApi _hospitalApi,*/ CGGYW007App _cggyw007App, BMZXX009App _bmzxx009App, RefundOrderApp _refundOrderApp, PayToolsApp _payToolsApp, BMZXX006App _bmzxx006App, BMZXX003App _bmzxx003App, CMZXX001App _cmzxx001App, CMZXX002App _cMZXX002App, ICacheContext _cache)
        {
            qrApp = _qrApp;
            bmzxx006App = _bmzxx006App;
            bmzxx003App = _bmzxx003App;

            payorderZYApp = _payorderZYApp;
            //hospitalApi = _hospitalApi;

            payToolsApp = _payToolsApp;
            cggyw007App = _cggyw007App;
            bmzxx009App = _bmzxx009App;
            refundOrderApp = _refundOrderApp;
            cmzxx001App = _cmzxx001App;
            cMZXX002App = _cMZXX002App;
            cache = _cache;
        }
        /// <summary>
        /// 住院付款二维码
        /// </summary>
        /// <param name="patid"></param>
        /// <param name="name"></param>
        /// <param name="phone"></param>
        /// <param name="card"></param>
        /// <param name="amount"></param>
        /// <param name="blh">病历号</param>
        /// <returns></returns>
        [HttpGet]
        public Response GetQRZY(string patid, string name, string phone, string card, float amount, string blh, string jzlsh)
        {
            var result = new Response<PaySecond>();
            //查询住院患者就诊记录(PATID)
            //HospitalApi api = new HospitalApi();
            //var res = JsonConvert.DeserializeObject<zyjlsResult>(api.GETZYJLPAT(patid, name, "1"));
            //if (res.success != true)
            //{
            //    result.Result.SUCCESS = "false";
            //    result.Code = 400;
            //    result.Message = res.message;
            //    return result;

            //}
            //else
            //{
            //    var jzlshReal = res.zyjls.Where(x => x.jzlsh == jzlsh).FirstOrDefault();
            //    if (jzlshReal == null)
            //    {
            //        result.Result.SUCCESS = "false";
            //        result.Code = 400;
            //        result.Message = jzlsh + "错误";
            //        return result;
            //    }
            //}

     
            //返回流水号
            PaySecond paySecond = qrApp.GetQR(patid, name, phone, card, amount, QrType.ZY);
            //本地数据库写入一条数据0=新建订单，1=建行成功，2=卫宁his成功
            payorderZYApp.Add(new AddOrUpdatePayOrderZYReq()
            {
                OrderNumber = paySecond.ORDERID,
                bxh = card,
                blh = blh,
                jzlsh = jzlsh,
                hzxm = name,
                zfPhone = phone,
                patid = patid,
                zfje = amount,
                zfzt = 0,
                time = DateTime.Now,
            });
            result.Result = new PaySecond
            {
                SUCCESS = "true",
                ORDERID = paySecond.ORDERID,
                QRURL = paySecond.QRURL,
                jzlsh = jzlsh
            };
            return result;
        }
        /// <summary>
        /// 付款成功后查询订单是否充值成功用的方法
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="patid"></param>
        /// <returns></returns>
        [HttpGet]
        public string QueryState(string orderId, string patid)
        {

            //log.Debug($"[Action] Query,[参数]{orderId}");
            var order = payorderZYApp.GetchargeState(orderId, patid);
            if (order)
            {
                return new { SUCCESS = true, Message = "充值成功！" }.ToJson();
            }
            else
            {
                return new { SUCCESS = false, Message = "充值失败！" }.ToJson();
            }

        }

        /// <summary>
        /// 轮询建行充值
        /// </summary>
        [HttpGet]
        public int CheckRechargeJh()
        {
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "充值定时执行JH");
            var orders = payorderZYApp.GetListByzfzt(0);
            foreach (var order in orders)
            {
                try
                {
                    //查询建行本订单金额
                    string returnStr = payToolsApp.GetOrder(order.OrderNumber);
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号：" + order.OrderNumber + "订单状态" + order.zfzt
                              + "患者姓名" + order.hzxm + "\r\n" + returnStr);
                    //建行订单状态 成功000000
                    var code = xmlToolApp.GetTextBydoc(returnStr, "RETURN_CODE");
                    log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "reutrncode:" + code);

                    if (code == "000000")
                    {
                        var pay = xmlToolApp.GetTextBydoc(returnStr, "PAYMENT_MONEY").ToDouble();
                        //已经退款金额
                        var refund = xmlToolApp.GetTextBydoc(returnStr, "REFUND_MONEY").ToDouble();
                        //退款备注
                        var msg = xmlToolApp.GetTextBydoc(returnStr, "RETURN_MSG");
                        //充值金额减去已经退款金额=现在在建行账上还剩余的金额
                        double krefund = pay - refund;
                        //建行端此笔款状态
                        var sate = xmlToolApp.GetTextBydoc(returnStr, "ORDER_STATUS");
                        if (order.zfje != null && sate == "1" && pay == order.zfje)
                        {
                            order.zfzt = 1;
                            payorderZYApp.Update(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[JH充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "充值成功:修改状态");
                        }

                    }

                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "建行充值请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);

                }
            }

            return 0;
        }

        /// <summary>
        /// 轮询his充值
        /// </summary>
        [HttpGet]
        public int CheckRechargeHis()
        {
            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "充值定时执行HIS");
            var orders = payorderZYApp.GetListByzfzt(1);
            foreach (var order in orders)
            {
                try
                {
                    HospitalApi hospitalApi = new HospitalApi();
                    //如果没有预充值
                    if (string.IsNullOrEmpty(order.hisddh) && string.IsNullOrEmpty(order.yjlsh))
                    {
                        var res = JsonConvert.DeserializeObject<PUTZYYJJYSResult>(hospitalApi.PUTZYYJJYS(order.jzlsh, order.hzxm));

                        if (res.success)
                        {
                            order.hisddh = res.hisddh;
                            order.yjlsh = res.yjlsh;
                            payorderZYApp.Update(order);
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + "患者姓名:" + order.hzxm + "预充值成功:修改单号");
                        }
                        else
                        {
                            log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",预充值失败:" + res.message);
                        }
                    }

                    //住院预交金充值
                    var res1 = JsonConvert.DeserializeObject<PUTZYYJJYSResult>(hospitalApi.PUTZYYJJ(new PUTZYYJJ_Input()
                    {
                        hzxm = order.hzxm,
                        jzlsh = order.jzlsh,
                        yjlsh = order.yjlsh,
                        hisddh = order.hisddh,
                        ptlsh = order.OrderNumber,//----------------
                        zffs = "2",
                        zfje = order.zfje.ToString() ?? "0",
                        zflsh = order.OrderNumber,//---------------
                        zfsj = "",//-----------
                        lxdh = order.zfPhone,
                        lxrxm = order.hzxm,
                        //lxrzjh = order.Id
                    }));
                    if (res1.success)
                    {
                        order.zfzt = 2;
                        payorderZYApp.Update(order);
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值成功");
                    }
                    else
                    {
                        log.Debug("日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "[HIS充值]--充值单号:" + order.OrderNumber + ",充值失败:" + res1.message);
                    }
                }
                catch (Exception e)
                {
                    string strError = "日期:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "HIS充值请求单号：" + order.OrderNumber + "错误信息：" + e.Message + "\r\n";
                    log.Warn(strError);
                }
            }
            return 0;
        }
    }
}
